package cn.gov.pbc.gd.credit.user.service.user.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.liu.jbase.PageListVo;
import com.liu.jbase.ResultVo;
import com.liu.jbase.annotation.LogAnnotation;
import com.liu.jbase.constant.ResCode;
import com.liu.jbase.service.impl.BaseServiceImpl;
import com.liu.tools.LogUtil;
import com.liu.tools.MD5Util;
import com.liu.tools.NetHelper;
import com.liu.tools.PrimaryUtil;
import com.liu.tools.RandomUtil;
import com.liu.tools.StrUtil;
import com.liu.tools.pinyin.HanyuPinyinHelper;

import cn.gov.pbc.gd.credit.api.notice.INoticeApi;
import cn.gov.pbc.gd.credit.api.user.IUserApi;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.common.constant.CommonConstant;
import cn.gov.pbc.gd.credit.common.constant.ConfConstant;
import cn.gov.pbc.gd.credit.common.constant.LogConstant;
import cn.gov.pbc.gd.credit.common.model.UserModel;
import cn.gov.pbc.gd.credit.common.service.redis.IRedisService;
import cn.gov.pbc.gd.credit.common.util.UserUtil;
import cn.gov.pbc.gd.credit.user.service.user.IUserService;
import cn.gov.pbc.gd.credit.vo.notice.NoticeVo;
import cn.gov.pbc.gd.credit.vo.user.ResUserVo;
import cn.gov.pbc.gd.credit.vo.user.UserVo;

@Service
public class UserServiceImpl extends BaseServiceImpl<ResUserVo, UserVo, IUserApi> implements IUserService{
	
	private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private IUserApi userApi;
	
	@Autowired
	private IRedisService redisService;	
	
	@Autowired
	private INoticeApi noticeApi;
	
	private Executor executor = Executors.newFixedThreadPool(5);

	@Override
	public ResultVo<PageListVo<ResUserVo>> page(UserVo record, PageListVo<ResUserVo> page, HttpServletRequest request) {

		UserModel userModel = UserUtil.getUserModel(record.getSid(), redisService);
		record.setCorpId(userModel.getCorpId());
		return super.page(record, page, request);
	}
	
	@LogAnnotation(moduleName=LogConstant.MODULE_USER, option=LogConstant.ADD, logType = LogConstant.LOG_OPERATE, content="添加虚拟用户")
	@Override
	public ResultVo<ResUserVo> add(UserVo vo, HttpServletRequest request) {
		
		ResultVo<ResUserVo> resultVo = new ResultVo<>();
		
		if (vo == null || StrUtil.isNull(vo.getAccount(), vo.getUserPwd(), vo.getUserName())) {
			
			logger.error(LogUtil.msg("UserServiceImpl:add", "请求参数不正确"));
			resultVo.setCode(ResCode.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
		}
		
		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		vo.setId(PrimaryUtil.primaryId("U"));
		vo.setSalt(RandomUtil.randomStr(6));
		vo.setUserPwd(UserUtil.getPwd(vo.getId(), vo.getUserPwd(), vo.getSalt()));
		vo.setCreateIp(NetHelper.getIpAddr(request));
		vo.setNamePinyin(HanyuPinyinHelper.toHanyuPinyin(vo.getUserName()));
		vo.setCreateTime(new Date());
		vo.setUpdateTime(new Date());
		vo.setProposerId(userModel.getUserId());
		vo.setApplyTime(new Date());
		vo.setStatus(0);
		
		if(StrUtil.isNotNull(vo.getStartRange()) && StrUtil.isNotNull(vo.getEndRange())){
			vo.setAllowIpRange(vo.getStartRange() + "-" +  vo.getEndRange());
		}
		resultVo.setCode(CodeConstant.FAIL);
		try {
			int flag = userApi.insert(vo);
			if(flag > 0){
				resultVo.setCode(CodeConstant.SUCCESS);
			} 
			
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					//添加新用户成功后在notice表插入新数据等待审核
					NoticeVo noticeVo=new NoticeVo();
					noticeVo.setId(PrimaryUtil.primaryId("R"));
					noticeVo.setSourceId(vo.getId());
					noticeVo.setCorpId(userModel.getCorpId());
					noticeVo.setContent(userModel.getCorpName() + "的" +userModel.getAccount() + "新增了" + vo.getAccount() + "的用户审核");
					//noticeVo.setNoticeUserId(noticeUserId);
					noticeVo.setNoticeType(CommonConstant.NOTICE_TYPE_ADD_USER);
					noticeVo.setNoticeFlag(1);
					noticeVo.setStatus(1);
					noticeVo.setApproveStatus(0);
					noticeVo.setCreateBy(userModel.getUserId());
					noticeVo.setCreateTime(new Date());
					noticeVo.setUpdateBy(userModel.getUserId());
					noticeVo.setUpdateTime(new Date());
					try {
						noticeApi.insert(noticeVo);
					} catch (Exception e) {
						logger.error(LogUtil.msg("UserServiceImpl:add", "添加通知信息异常"), e);
					}
					
				}
			});
			
		} catch (Exception e) {
			logger.error(LogUtil.msg("UserServiceImpl:add", "添加用户异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
		}
		
		return resultVo;
	}
		
	
	@LogAnnotation(moduleName=LogConstant.MODULE_USER, option=LogConstant.UPDATE, logType = LogConstant.LOG_OPERATE, content="修改虚拟用户")
	@Override
	public ResultVo<ResUserVo> update(UserVo vo, HttpServletRequest request) {
		
		ResultVo<ResUserVo> resultVo = new ResultVo<>();
		if (vo == null || StrUtil.isNull(vo.getAccount(), vo.getUserName(), vo.getCorpId(),vo.getDeptId(),vo.getOfficePhone(), vo.getAllowIp())) {
			logger.error(LogUtil.msg("UserServiceImpl:update", "请求参数不正确"));
			resultVo.setCode(ResCode.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
		}
		
		vo.setUpdateTime(new Date());
		if(StrUtil.isNotNull(vo.getStartRange()) && StrUtil.isNotNull(vo.getEndRange())){
			vo.setAllowIpRange(vo.getStartRange() + "-" +  vo.getEndRange());
		}
		resultVo.setCode(CodeConstant.FAIL);
		try {
			
			vo.setIsModify(1);
			int flag = userApi.update(vo);
			if(flag > 0){
				resultVo.setCode(CodeConstant.SUCCESS);
			} 
		} catch (Exception e) {
			logger.error(LogUtil.msg("UserServiceImpl:update", "修改用户异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
		}
		return resultVo;
	}
	
	@LogAnnotation(moduleName=LogConstant.MODULE_USER, option=LogConstant.DEL, logType = LogConstant.LOG_OPERATE, content="删除虚拟用户")
	@Override
	public ResultVo<ResUserVo> delete(UserVo vo, HttpServletRequest request) {
		
		return super.delete(vo, request);
	}
	
	@Override
	public ResultVo<ResUserVo> modifyPwd(UserVo vo) {

		ResultVo<ResUserVo> result = new ResultVo<>();
		
		String id = vo.getId();//取用户id
		
		ResUserVo resUserVo = userApi.queryById(id);//到虚拟用户数据库表中查用户信息
		
		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);//从服务器缓存取到用户信息
		
		if(!userModel.getUserId().equals(id)){//判断是否为当前操作用户
			
			result.setMsg("必须本人修改密码");
			
			return result;
		}
		
		//如果虚拟用户不为空
		if(resUserVo != null){
			
			String md5OldPwd = UserUtil.getPwd(vo.getId(), MD5Util.MD5(vo.getOldPwd()), resUserVo.getSalt());//原始密码
			
			if(!resUserVo.getUserPwd().equals(md5OldPwd)){//判断用户的原始密码是否正确
				
				result.setCode("MISSPWD");
				
				return result;
			}
			String md5Pwd = UserUtil.getPwd(vo.getId(), MD5Util.MD5(vo.getUserPwd()), resUserVo.getSalt());//新密码
			
			vo.setUserPwd(md5Pwd);//设置新密码
			vo.setUpdatePwdCount(resUserVo.getUpdatePwdCount() == null ? 1 : resUserVo.getUpdatePwdCount() + 1);
			vo.setIsModifyRole(0);
			int flagInt = userApi.update(vo);
			
			if(flagInt>0){
				
				result.setCode("SUCCESS");
				
				return result;
			}
		}
		
		result.setCode("ERROR");//修改未完成，未知错误。
		result.setMsg("网络故障，请稍后再试。");
		
		return result;
	}

	@Override
	public ResultVo<ResUserVo> defaultPwd(UserVo vo, HttpServletRequest request) {

		ResultVo<ResUserVo> result = new ResultVo<>();
		
		String id = vo.getId();//取用户id
		
		ResUserVo resUserVo = userApi.queryById(id);//到虚拟用户数据库表中查用户信息
				
		//如果虚拟用户不为空
		if(resUserVo != null){
				
			String md5Pwd = UserUtil.getPwd(vo.getId(), MD5Util.MD5(ConfConstant.creditDefaultPwd), resUserVo.getSalt());//新密码
			
			vo.setUserPwd(md5Pwd);//设置新密码
			vo.setUpdatePwdCount(0);
			vo.setIsModifyRole(0);
			int flagInt = userApi.update(vo);
			
			if(flagInt>0){
				
				result.setCode("SUCCESS");
				
				return result;
			}
		}
		
		result.setCode("ERROR");//修改未完成，未知错误。
		result.setMsg("网络故障，请稍后再试。");
		
		return result;
	}
	
	@LogAnnotation(moduleName=LogConstant.MODULE_USER, option=LogConstant.UPDATE, logType = LogConstant.LOG_OPERATE, content="修改用户状态")
	@Override
	public ResultVo<ResUserVo> updateStatus(UserVo vo, HttpServletRequest request) {
		
		
		ResultVo<ResUserVo> resultVo = new ResultVo<>();
        if(vo == null || StrUtil.isNull(vo.getSid())){
        	
        	logger.error(LogUtil.msg("UserServiceImpl:updateStatus", "请求参数不正确"));
			resultVo.setCode(ResCode.FAIL);
			return resultVo;
        }
        
        UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
        
        vo.setUserId(userModel.getUserId());
        vo.setCorpId(userModel.getCorpId());
        
        try {
			userApi.updateStatus(vo);
		} catch (Exception e) {
			
			logger.error(LogUtil.msg("UserServiceImpl:updateStatus", "修改用户状态异常"), e);
			resultVo.setCode(ResCode.EXCEPTION);
			return resultVo;
		}
        
        resultVo.setCode(CodeConstant.SUCCESS);
        
		return resultVo;
	}
	

	@Override
	public ResultVo<String> updateHeadImg(UserVo vo, HttpServletRequest request) {
		
		ResultVo<String> resultVo = new ResultVo<>();
		if (vo == null || StrUtil.isNull(vo.getHeadUrl())) {
			logger.error(LogUtil.msg("UserServiceImpl:updateHeadImg", "请求参数不正确"));
			resultVo.setCode(ResCode.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
		}
		
		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);

		resultVo.setCode(CodeConstant.FAIL);
		try {
			vo.setId(userModel.getUserId());
			vo.setIsModifyRole(0);
			int flag = userApi.update(vo);
			if(flag > 0){
				resultVo.setCode(CodeConstant.SUCCESS);
			} 
		} catch (Exception e) {
			logger.error(LogUtil.msg("UserServiceImpl:updateHeadImg", "修改用户头像"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
		}
		
		return resultVo;
	}

	@Override
	public ResultVo<String> userSign(UserVo vo, HttpServletRequest request) {
		
		ResultVo<String> resultVo = new ResultVo<>();
		if (vo == null || StrUtil.isNull(vo.getId())) {
			logger.error(LogUtil.msg("UserServiceImpl:userSign", "请求参数不正确"));
			resultVo.setCode(ResCode.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
		}
		
		vo.setUpdateTime(new Date());

		resultVo.setCode(CodeConstant.FAIL);
		try {
			
			vo.setIsModifyRole(0);
			int flag = userApi.update(vo);
			if(flag > 0){
				resultVo.setCode(CodeConstant.SUCCESS);
			} 
		} catch (Exception e) {
			logger.error(LogUtil.msg("UserServiceImpl:userSign", "用户签名异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
		}
		return resultVo;
	}

	@Override
	public ResultVo<List<ResUserVo>> queryOperaterList(UserVo vo, HttpServletRequest request) {
       
		List<ResUserVo> resUserVo  = userApi.queryOperaterList(vo); 
		
		ResultVo<List<ResUserVo>> resultVo = new ResultVo<>();
		resultVo.setCode(ResCode.SUCCESS);
		resultVo.setData(resUserVo);
		return resultVo;
	}


}
